package com.lzk.jetpacktest.update

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import com.lzk.jetpacktest.R
import com.lzk.jetpacktest.databinding.ActivityVerificationCodeBinding
import com.lzk.jetpacktest.databinding.ActivityVersionUpdateBinding

class VersionUpdateActivity : AppCompatActivity() {

    private lateinit var mBinding: ActivityVersionUpdateBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = DataBindingUtil.setContentView(this,R.layout.activity_version_update)

        mBinding.btnUpdate.setOnClickListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
                update()
            }else{
                if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
                    update()
                }else{
                    ActivityCompat.requestPermissions(this,
                        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),1001)
                }
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1001){
            if (grantResults.isNotEmpty()
                && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                update()
            }
        }
    }

    private fun update(){
        AppUpdateUtils.getInstance().downloadApk("https://www.wanandroid.com/blogimgs/aa0da019-c965-4c8a-8919-198397e0c3f1.apk","app.apk")
    }
}